<template>
  <div class="UpDatePhoto-wrap">
    <img :src="image" ref="avatar" class="img" />
    <van-nav-bar
      left-text="退出"
      right-text="完成"
      class="nvbus"
      @click-left="$emit('close')"
      @click-right="onClickRight"
    />
  </div>
</template>
<script>
import { changeUserPhoto } from "../../../api/profile";
/*cropperjs css */
import "cropperjs/dist/cropper.css";
/*cropperjs js */
import Cropper from "cropperjs";
export default {
  name: "UpdatePhoto",
  data() {
    return {
      image: window.URL.createObjectURL(this.photoView),
      cropper: null,
    };
  },
  props: {
    photoView: {
      required: true,
    },
  },
  components: {},
  mounted() {
    this.previewOpen();
  },
  methods: {
    //图片裁切的配置项，页面以上来就加载
    //将cropper放到data中，这样整个组件都可以访问的到
    previewOpen() {
      const image = this.$refs.avatar;
      this.cropper = new Cropper(image, {
        viewMode: 1, //查看模式
        dragMode: "move", //移动模式
        aspectRatio: 1, //裁切框大小比例
        cropBoxMovable: false, //裁切框是否可以移动
        cropBoxResizable: false, //裁切框是否可以改变大小
        background: false, //背景颜色
        movable: true, //是否可以移动
      });
    },

    //获取裁切后的图片大小，方法是固定的(设置成promise是为了不用嵌套)
    getCroppedCanvas() {
      return new Promise((resolve) => {
        this.cropper.getCroppedCanvas().toBlob((blob) => {
          resolve(blob);
        });
      });
    },

    //完成
    async onClickRight() {
      const file = await this.getCroppedCanvas();
      const params = new FormData();//创建一个formData
      params.append("photo", file);//photo是传给后端的key值；file是文件对象；
      await changeUserPhoto(params)//向后端发送请求
      this.$emit("close");//关闭pop
      let body = window.URL.createObjectURL(file); //它是一个文件对象，所以需要改一下（是用来前端预览的）
      this.$emit("changeImage", body);//通知父组件，更新视图
      this.$toast.success("修改成功");
    },
  },
};
</script>
<style scoped lang="less">
.UpDatePhoto-wrap {
  .nvbus {
    position: fixed;
    right: 0;
    left: 0;
    bottom: 0;
    background: black;
  }
}
.img {
  display: block;
  max-width: 100%;
}
</style>